package server.communication.listeners;

import java.sql.SQLException;
import java.sql.Statement;

import server.Server;
import server.threads.ServerCommunicator;
import message.Message;
import message.ServerMessageWrapper;
import message.UpdateDataRequestMessage;
import message.UpdateDataResponseMessage;
import communication.MessageListener;
import communication.MessageReceivedEvent;

public class UpdateDataListener implements MessageListener
{
	private final ServerCommunicator communicator;
	private final Server server;
	
	public UpdateDataListener(ServerCommunicator communicator, Server server)
	{
		this.communicator = communicator;
		this.server = server;
	}
	
	private boolean updatePassword(int id, String username, String password)
	{
		java.sql.Connection dbConnection = server.getDatabaseConnection();
		boolean success = false;
		
		try
		{
			Statement statement = dbConnection.createStatement();
			
			if (id > 0)
				statement.execute("UPDATE users SET userId='" + id + "' WHERE username='" + username + "'");
			
			statement.execute("UPDATE users SET password='" + password + "' WHERE username='" + username + "'");
			
			success = statement.getUpdateCount() > 0;
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		return success;
	}
	@Override
	public void messageRecieved(MessageReceivedEvent e)
	{
		ServerMessageWrapper message = ((ServerMessageWrapper) e.getMessage());
		UpdateDataRequestMessage innerMessage = (UpdateDataRequestMessage) message.internalMessage;
		UpdateDataResponseMessage responseMessage = new UpdateDataResponseMessage();
		boolean success = updatePassword(innerMessage.getId(), innerMessage.getUsername(), innerMessage.getPassword());
		
		if (success)
		{
			server.dataSynchronized();
			
			if (!message.sentByServer)
				communicator.broadcastToServers(innerMessage);
		}
		
		responseMessage.setSuccess(success);
		
		communicator.sendMessage(message.connectionId, responseMessage);
		
		server.dataSynchronized();
	}

	@Override
	public boolean acceptsMessage(Message message)
	{
		if (message.getClass().equals(ServerMessageWrapper.class))
			message = ((ServerMessageWrapper) message).internalMessage;
		
		return message.getClass().equals(UpdateDataRequestMessage.class);
	}
}
